﻿using BenCaoXuan.Infrastructure.Attr;
using BenCaoXuan.Infrastructure.Dto;
using BenCaoXuan.Infrastructure.Dto.Admin.employee;
using BenCaoXuan.Infrastructure.Dto.PC;
using BenCaoXuan.Infrastructure.EFCore.MySql;
using BenCaoXuan.Infrastructure.IOC;
using BenCaoXuan.Infrastructure.Redis;
using BenCaoXuan.Infrastructure.Tools;
using BenCaoXuan.Service.Interface.PC;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BenCaoXuan.Service.Instance.PC
{
    [Inject_]
    public class Order_Service : Base_Service, I_Order_Service
    {
        private readonly Order_IOC _order_IOC;
        private readonly Product_IOC _product_IOC;
        private readonly Sys_IOC _sys_IOC;
        private readonly Login_IOC _login_IOC;

        public Order_Service(Order_IOC order_IOC, Product_IOC product_IOC, Sys_IOC sys_IOC, Login_IOC login_IOC)
        {
            _order_IOC = order_IOC;
            _product_IOC = product_IOC;
            _sys_IOC = sys_IOC;
            _login_IOC = login_IOC;
        }

        /// <summary>
        /// 获取所有订单数据
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Order(Orders_Dto dto)
        {
            //订单表
            var orders = await _order_IOC._orders_EFCore.GetAll(out int total, dto.page, dto.limit, false, d => d.OCreateTime, d => d.OCustomerName.Contains(dto.key) || d.OCustomerPhone.Contains(dto.key))
                .Select(d => new
                {
                    d.OId, // 订单id
                    d.OCustomerName, // 客户名字
                    d.OCustomerPhone, // 客户电话
                    CreateTime = d.OCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    d.OPayType, // 支付id
                }).ToListAsync();

            //字典表
            var payDict = await _sys_IOC._sysDictionary_EFCore.GetAll()
                .ToDictionaryAsync(d => d.DId, d => d.DName);

            //订单详情表
            var orderDetails = await _order_IOC._ordersDetails_EFCore.GetAll().ToListAsync();

            // 套餐表
            var packageDict = await _product_IOC._productPackage_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PpId, d => d.PpName);

            // 产品表
            var productDict = await _product_IOC._product_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PId, d => d.PName);

            // 产品规格表
            var productSpecsDict = await _product_IOC._productSpecs_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PsId, d => new { d.PsName, d.PsProductId });

            // 构建最终结果
            var result = orders.Select(order => new
            {
                id = order.OId,
                name = order.OCustomerName,
                phone = order.OCustomerPhone,
                time = order.CreateTime,
                pay = payDict.ContainsKey(order.OPayType) ? payDict[order.OPayType] : "未支付",
                services = orderDetails.Where(od => od.OdOrderId == order.OId)
                    .Select(od =>
                    {
                        var servicesList = new List<string>();

                        // 处理套餐
                        if (!string.IsNullOrEmpty(od.OdPackageId))
                        {
                            var packageIds = od.OdPackageId.Split(',');
                            foreach (var packageId in packageIds)
                            {
                                if (packageDict.ContainsKey(packageId))
                                {
                                    servicesList.Add(packageDict[packageId]);
                                }
                            }
                        }

                        // 处理产品规格
                        if (!string.IsNullOrEmpty(od.OdProductId))
                        {
                            var productSpecIds = od.OdProductId.Split(',');
                            foreach (var productSpecId in productSpecIds)
                            {
                                if (productSpecsDict.ContainsKey(productSpecId))
                                {
                                    var productSpec = productSpecsDict[productSpecId];
                                    if (productDict.ContainsKey(productSpec.PsProductId))
                                    {
                                        servicesList.Add($"{productDict[productSpec.PsProductId]}({productSpec.PsName})");
                                    }
                                }
                            }
                        }

                        return string.Join(" + ", servicesList);
                    }).FirstOrDefault() ?? "无服务"
            }).ToList();

            return Get_Result(1, "ok", new
            {
                total = total,
                data = result
            });
        }
        /// <summary>
        /// 订单详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Api_Result_Dto> Get_Order_Detail(string id)
        {
            //订单表
            var orders = await _order_IOC._orders_EFCore.GetAll(d => d.OId == id)
                .Select(d => new
                {
                    d.OId, // 订单id
                    d.OCustomerName, // 客户名字
                    d.OCustomerPhone, // 客户电话
                    CreateTime = d.OCreateTime.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    d.OPayType, // 支付id

                    d.OEmployeeArtId, // 理疗师id
                    d.OEmployeeFrontId, // 前台id
                    d.OIsAppointment, // 是否预约转订单 0-否 1-是
                    d.OOrderStatus, // 订单状态 0-进行中 1-已完成
                    d.OPayStatus, // 支付状态 0-待支付 1-已支付
                    d.ORoomId, // 房间id

                    d.OTotalAmount,
                    CompleteTime = d.OCompleteTime.Value.ToString("yyyy-MM-dd HH:mm:ss"), // 订单完成时间
                }).ToListAsync();

            // 字典表
            var payDict = await _sys_IOC._sysDictionary_EFCore.GetAll()
                .ToDictionaryAsync(d => d.DId, d => d.DName);

            // 订单详情表
            var orderDetails = await _order_IOC._ordersDetails_EFCore.GetAll().ToListAsync();

            // 套餐表
            var packageDict = await _product_IOC._productPackage_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PpId, d => d.PpName);

            // 产品表
            var productDict = await _product_IOC._product_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PId, d => d.PName);

            // 产品规格表
            var productSpecsDict = await _product_IOC._productSpecs_EFCore.GetAll()
                .ToDictionaryAsync(d => d.PsId, d => new { d.PsName, d.PsProductId });

            // 员工表（包含理疗师和前台）
            var employeeDict = await _login_IOC._sysEmployee_EFCore.GetAll()
                .ToDictionaryAsync(d => d.EId, d => d.EName);

            // 房间表
            var roomDict = await _order_IOC._room_EFCore.GetAll()
                .ToDictionaryAsync(d => d.RId, d => d.RName);

            // 构建最终结果
            var result = orders.Select(order => new
            {
                id = order.OId,
                name = order.OCustomerName,
                phone = order.OCustomerPhone,
                time = order.CreateTime,
                pay = payDict.ContainsKey(order.OPayType) ? payDict[order.OPayType] : "未支付",
                CompleteTime = order.CompleteTime,
                money = order.OTotalAmount,

                // 理疗师名称
                therapistName = employeeDict.ContainsKey(order.OEmployeeArtId) ? employeeDict[order.OEmployeeArtId] : "未知",
                // 前台名称
                frontName = employeeDict.ContainsKey(order.OEmployeeFrontId) ? employeeDict[order.OEmployeeFrontId] : "未知",
                // 是否预约转订单
                isAppointment = order.OIsAppointment == 1 ? "是" : "否",
                // 订单状态
                orderStatus = order.OOrderStatus == 1 ? "已完成" : "进行中",
                // 支付状态
                payStatus = order.OPayStatus == 1 ? "已支付" : "待支付",
                // 房间名称
                roomName = roomDict.ContainsKey(order.ORoomId) ? roomDict[order.ORoomId] : "未知",

                services = orderDetails.Where(od => od.OdOrderId == order.OId)
                    .Select(od =>
                    {
                        var servicesList = new List<string>();

                        // 处理套餐
                        if (!string.IsNullOrEmpty(od.OdPackageId))
                        {
                            var packageIds = od.OdPackageId.Split(',');
                            foreach (var packageId in packageIds)
                            {
                                if (packageDict.ContainsKey(packageId))
                                {
                                    servicesList.Add(packageDict[packageId]);
                                }
                            }
                        }

                        // 处理产品规格
                        if (!string.IsNullOrEmpty(od.OdProductId))
                        {
                            var productSpecIds = od.OdProductId.Split(',');
                            foreach (var productSpecId in productSpecIds)
                            {
                                if (productSpecsDict.ContainsKey(productSpecId))
                                {
                                    var productSpec = productSpecsDict[productSpecId];
                                    if (productDict.ContainsKey(productSpec.PsProductId))
                                    {
                                        servicesList.Add($"{productDict[productSpec.PsProductId]}({productSpec.PsName})");
                                    }
                                }
                            }
                        }

                        return string.Join(" + ", servicesList);
                    }).FirstOrDefault() ?? "无服务"
            }).SingleOrDefault();

            return Get_Result(1, "ok", result);
        }
    }
}
